package org.track.web.validator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.track.web.entity.TrackRow;

/**
 * 
 * @author josdem (joseluis.delacruz@gmail.com)
 *
 */

public class TrackValidator implements Validator {
	private static final Log log = LogFactory.getLog(TrackValidator.class);
	private static final int MAX_TRACK_NUMBER = 100;

	public boolean supports(Class< ?> clazz) {
		return TrackRow.class.equals(clazz);
	}

	public void validate(Object target, Errors errors) {
		TrackRow track = (TrackRow) target;
		log.debug("From validate artist: " + track.getArtist());
		log.debug("From validate title: " + track.getTitle());
		log.debug("From validate album: " + track.getAlbum());
		log.debug("From validate trackNumber: " + track.getTrackNumber());
		log.debug("From validate length: " + track.getLength());
		ValidationUtils.rejectIfEmpty(errors, "artist", "artist.empty");
		if (track.getTrackNumber() < 0) {
			errors.rejectValue("trackNumber", "negativevalue");
			errors.pushNestedPath("trackNumber");
        } else {
			
			if (track.getTrackNumber() > MAX_TRACK_NUMBER) {
			    errors.rejectValue("trackNumber", "too.darn.old");
			    errors.pushNestedPath("trackNumber");
			}
		}
		if(track.getLength() < 0){
			errors.rejectValue("length", "negativevalue");
			errors.pushNestedPath("length");
		}
		if(errors.hasErrors()){	
			errors.popNestedPath();
		}
	}
}
